﻿using Nest;
using System;
using System.Linq.Expressions;

namespace Infrastructure.ElasticSearch.ParentChilds
{
    public class DateRangeSpecification<T> : ISearchSpecification<ISearchRequest<T>> where T : class
    {
        private readonly DateTime? _valueDateBegin;
        private readonly DateTime? _valueDateEnd;
        private readonly Expression<Func<T, string>> _field;

        public DateRangeSpecification(DateTime? valueDateBegin, DateTime? valueDateEnd, Expression<Func<T, string>> field)
        {
            _valueDateBegin = valueDateBegin;
            _valueDateEnd = valueDateEnd;
            _field = field;
        }

        public ISearchRequest<T> IsSatisfiedBy()
        {
            return new SearchDescriptor<T>()
                .Query(q => q
                    .DateRange(m =>
                        {
                            var res = m.Field(_field);
                            if (_valueDateBegin != null)
                                res.GreaterThanOrEquals(
                                    _valueDateBegin.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                            if (_valueDateEnd != null)
                                res.LessThanOrEquals(_valueDateEnd.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                            return res;
                        }
                    )
                );
        }
    }
}